﻿using System;
using System.Configuration;

namespace Salient.Web.Administration.AppConfig
{
    public partial class CreateAppSetting : ApplicationConfigurationPage
    {
        private WebAdminWithConfirmation Master
        {
            get { return (WebAdminWithConfirmation) base.Master; }
        }

        private void Page_Load()
        {
            if (!IsPostBack)
            {
                string appPath = ApplicationPath;
                if (!String.IsNullOrEmpty(appPath))
                {
                    AppSettingTitle.Text = String.Format((string) GetLocalResourceObject("TitleForSite"), appPath);
                }
            }
        }

        public void Save(object sender, EventArgs e)
        {
            if (!IsValid)
            {
                return;
            }

            System.Configuration.Configuration config = OpenWebConfiguration(ApplicationPath);
            var appSettingsSection = (AppSettingsSection) config.GetSection("appSettings");

            string name = AppSetting.Name;
            string value = AppSetting.Value;

            // Check if the name has already existed
            if (appSettingsSection.Settings[name] != null)
            {
                AppSetting.CustomValidator.IsValid = false;
                AppSetting.CustomValidator.ErrorMessage = (string) GetLocalResourceObject("SettingAlreadyDefinedError");
            }
            else
            {
                appSettingsSection.Settings.Add(name, value);

                SaveConfig(config);

                // Go to confirmation UI
                AppSettingConfirmation.Text = String.Format((string) GetLocalResourceObject("ConfirmationText"),
                                                            AppSetting.Name);
                Master.SetDisplayUI(true);
            }
        }

        // Confirmation's related handlers
        public void AddAnother_Click(object sender, EventArgs e)
        {
            AppSetting.ResetUI();
            Master.SetDisplayUI(false);
        }

        public void OK_Click(object sender, EventArgs e)
        {
            ReturnToPreviousPage(sender, e);
        }
    }
}